<template>
  <view class="workorder-detail-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <text class="nav-back" @click="goBack">返回</text>
      <text class="nav-title">工单详情</text>
      <text class="nav-edit" @click="editWorkorder" v-if="workorderInfo.status === '已派单'">编辑</text>
    </view>

    <!-- 工单基本信息 -->
    <view class="detail-section">
      <view class="section-title">基本信息</view>
      <view class="info-card">
        <view class="info-row">
          <text class="info-label">工单ID：</text>
          <text class="info-value">{{ workorderInfo.id }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">报修类型：</text>
          <text class="info-value">{{ workorderInfo.repairType }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">工单状态：</text>
          <text class="info-value status" :class="getStatusClass(workorderInfo.status)">
            {{ workorderInfo.status }}
          </text>
        </view>
        <view class="info-row">
          <text class="info-label">创建时间：</text>
          <text class="info-value">{{ formatDate(workorderInfo.createTime) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">更新时间：</text>
          <text class="info-value">{{ formatDate(workorderInfo.updateTime) }}</text>
        </view>
      </view>
    </view>

    <!-- 房产信息 -->
    <view class="detail-section">
      <view class="section-title">房产信息</view>
      <view class="info-card">
        <view class="info-row">
          <text class="info-label">房产ID：</text>
          <text class="info-value">{{ workorderInfo.houseId }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">合同编号：</text>
          <text class="info-value">{{ workorderInfo.htbh }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">业主姓名：</text>
          <text class="info-value">{{ workorderInfo.jzxm }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">业主手机：</text>
          <text class="info-value">{{  workorderInfo.landlordPhone }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">详细地址：</text>
          <text class="info-value address">{{ getFullAddress() }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">门禁编码：</text>
          <text class="info-value">{{ workorderInfo.door || workorderInfo.address }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">月费金额：</text>
          <text class="info-value price">¥{{ workorderInfo.monthPrice || 0 }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">宽带账号：</text>
          <text class="info-value">{{ workorderInfo.kdzh }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">宽带密码：</text>
          <text class="info-value">{{ workorderInfo.kdmm }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">门禁编码：</text>
          <text class="info-value">{{ workorderInfo.mjbm || '暂无' }}</text>
        </view>
        <view class="info-row" v-if="workorderInfo.createPhone">
          <text class="info-label">保障电话：</text>
          <text class="info-value">{{ workorderInfo.createPhone }}</text>
        </view>
      </view>
    </view>

    <!-- 报修内容 -->
    <view class="detail-section">
      <view class="section-title">报修内容</view>
      <view class="info-card">
        <view class="info-row">
          <text class="info-label">报修描述：</text>
          <text class="info-value description">{{ workorderInfo.repairContent }}</text>
        </view>
        <view class="info-row" v-if="workorderInfo.repairImgs && workorderInfo.repairImgs.trim()">
          <text class="info-label">报修图片：</text>
          <view class="image-list">
            <image 
              v-for="(img, index) in getImageList()" 
              :key="index"
              :src="img"
              mode="aspectFill"
              class="repair-image"
              @click="previewImage(img, getImageList())"
              @error="onImageError(img, index)"
            />
          </view>
        </view>
        <view class="info-row" v-else>
          <text class="info-label">报修图片：</text>
          <text class="info-value">暂无图片</text>
        </view>
      </view>
    </view>

    <!-- 处理信息 -->
    <view class="detail-section" v-if="workorderInfo.responseContent">
      <view class="section-title">处理信息</view>
      <view class="info-card">
        <view class="info-row">
          <text class="info-label">处理回复：</text>
          <text class="info-value description">{{ workorderInfo.responseContent }}</text>
        </view>
      </view>
    </view>

    <!-- 人员信息 -->
    <view class="detail-section">
      <view class="section-title">人员信息</view>
      <view class="info-card">
        <view class="info-row">
          <text class="info-label">申请人：</text>
          <text class="info-value">{{ workorderInfo.createByNickname }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">申请人类型：</text>
          <text class="info-value">{{ getCreateUserTypeText(workorderInfo.createUserType) }}</text>
        </view>
        <view class="info-row" v-if="workorderInfo.operaUseNickname">
          <text class="info-label">处理人：</text>
          <text class="info-value">{{ workorderInfo.operaUseNickname }}</text>
        </view>
        <view class="info-row" v-if="workorderInfo.operaUserId">
          <text class="info-label">处理人ID：</text>
          <text class="info-value">{{ workorderInfo.operaUserId }}</text>
        </view>
      </view>
    </view>

    <!-- 系统信息 -->
    <view class="detail-section">
      <view class="section-title">系统信息</view>
      <view class="info-card">
        <view class="info-row">
          <text class="info-label">创建人：</text>
          <text class="info-value">{{ workorderInfo.createBy }}</text>
        </view>
        <view class="info-row" v-if="workorderInfo.updateBy">
          <text class="info-label">更新人：</text>
          <text class="info-value">{{ workorderInfo.updateBy }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">ADSL ID：</text>
          <text class="info-value">{{ workorderInfo.adslId }}</text>
        </view>
      </view>
    </view>

    <!-- 操作日志 -->
    <view class="detail-section" v-if="workorderInfo.logs && workorderInfo.logs.length > 0">
      <view class="section-title">
        <text class="iconfont icon-clock"></text>
        处理记录
      </view>
      <view class="timeline-card">
        <view class="timeline-item" v-for="(log, index) in workorderInfo.logs" :key="log.id">
          <view class="timeline-dot" :class="getTimelineDotClass(log.status)"></view>
          <view class="timeline-line" v-if="index < workorderInfo.logs.length - 1"></view>
          <view class="timeline-content">
            <view class="timeline-status-tag" :class="getStatusTagClass(log.status)">
              {{ log.status }}
            </view>
            <view class="timeline-time-short">{{ formatTimeShort(log.createTime) }}</view>
            <view class="timeline-time-full">{{ formatDate(log.createTime) }}</view>
            <view class="timeline-operator">操作人: {{ log.createByNickName }}</view>
            <view class="timeline-log" v-if="log.log">{{ log.log }}</view>
            
            <!-- 已完成状态显示图片和位置信息 -->
            <view class="timeline-completion-info" v-if="log.status === '已完成'">
              <!-- 位置信息 -->
              <view class="location-info" v-if="log.longitude && log.latitude">
                <text class="info-label">位置：</text>
                <text class="location-coords">{{ log.longitude }}, {{ log.latitude }}</text>
              </view>
              
              <!-- 图片信息 -->
              <view class="completion-images" v-if="log.img && log.img.trim()">
                <text class="info-label">完成图片：</text>
                <view class="image-grid">
                  <image 
                    v-for="(imgUrl, imgIndex) in getCompletionImageList(log.img)" 
                    :key="imgIndex"
                    :src="imgUrl"
                    mode="aspectFill"
                    class="completion-image"
                    @click="previewCompletionImage(imgUrl, getCompletionImageList(log.img))"
                    @error="onCompletionImageError(imgUrl, imgIndex)"
                  />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <!-- <view class="bottom-actions" v-if="workorderInfo.status === '已派单' && !isStaff">
      <button class="action-btn accept" @click="acceptWorkorder">接受工单</button>
      <button class="action-btn reject" @click="rejectWorkorder">拒绝工单</button>
    </view> -->
  </view>
</template>

<script>
import { getRepairDetail } from '@/api/door/repair'
import config from '@/config'

export default {
  computed: {
    isStaff() {
      const roles = this.$store.state.user.roles || [];
      return roles.includes('yg');
    }
  },
  data() {
    return {
      workorderId: '',
      workorderInfo: {},
      mjbm: '' // 门禁编码
    }
  },
  onLoad(options) {
    if (options.id) {
      this.workorderId = options.id
      
      // 获取门禁编码参数
      if (options.mjbm) {
        this.mjbm = decodeURIComponent(options.mjbm)
        console.log('获取到门禁编码:', this.mjbm)
      }
      
      // 如果有传递的工单数据，先使用传递的数据
      if (options.workorderData) {
        try {
          const workorderData = JSON.parse(decodeURIComponent(options.workorderData))
          this.workorderInfo = { ...workorderData }
          console.log('使用传递的工单数据:', this.workorderInfo)
        } catch (error) {
          console.error('解析传递的工单数据失败:', error)
        }
      }
      
      // 加载详情数据（主要用于获取处理记录）
      this.loadDetail()
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    // 加载工单详情
    async loadDetail() {
      try {
        const response = await getRepairDetail(this.workorderId)
        if (response.code === 200) {
          const detailData = response.data || {}
          
          // 保留传递的数据，只更新处理记录
          this.workorderInfo = {
            ...this.workorderInfo, // 保留传递的数据
            logs: detailData.logs || [] // 只更新处理记录
          }
          
          console.log('工单详情数据:', this.workorderInfo)
          console.log('处理记录:', this.workorderInfo.logs)
          console.log('报修图片字段:', this.workorderInfo.repairImgs)
        } else {
          this.$modal.msgError(response.msg || '获取详情失败')
        }
      } catch (error) {
        console.error('加载工单详情失败:', error)
        this.$modal.msgError('网络异常，请稍后重试')
      }
    },
    
    // 编辑工单
    editWorkorder() {
      uni.navigateTo({
        url: `/pages/workorder/edit?id=${this.workorderId}`
      })
    },
    
    // 接受工单
    acceptWorkorder() {
      uni.showModal({
        title: '确认操作',
        content: '确定接受此工单吗？',
        success: (res) => {
          if (res.confirm) {
            // 这里需要调用接受工单的API
            this.$modal.msgSuccess('操作成功')
            this.loadDetail() // 刷新详情
          }
        }
      })
    },
    
    // 拒绝工单
    rejectWorkorder() {
      uni.showModal({
        title: '确认操作',
        content: '确定拒绝此工单吗？',
        success: (res) => {
          if (res.confirm) {
            // 这里需要调用拒绝工单的API
            this.$modal.msgSuccess('操作成功')
            this.loadDetail() // 刷新详情
          }
        }
      })
    },
    
    // 获取图片列表
    getImageList() {
      if (!this.workorderInfo.repairImgs) {
        return []
      }
      
      const images = this.workorderInfo.repairImgs.split(',').filter(img => img && img.trim())
      
      // 将fileName转换为完整的URL
      const imageUrls = images.map(fileName => {
        // 如果已经是完整URL，直接返回
        if (fileName.startsWith('http://') || fileName.startsWith('https://')) {
          return fileName
        }
        // 如果是相对路径，拼接基础URL
        return `http://charging-prod.szhansel.com/gzyunkong-api/${fileName}`
      })
      
      console.log('图片列表:', imageUrls)
      return imageUrls
    },
    
    // 获取完成图片列表
    getCompletionImageList(imgString) {
      if (!imgString) {
        return []
      }
      
      const images = imgString.split(',').filter(img => img && img.trim())
      
      // 将fileName转换为完整的URL
      const imageUrls = images.map(fileName => {
        // 如果已经是完整URL，直接返回
        if (fileName.startsWith('http://') || fileName.startsWith('https://')) {
          return fileName
        }
        // 如果是相对路径，拼接基础URL
        return `http://charging-prod.szhansel.com/gzyunkong-api/${fileName}`
      })
      
      console.log('完成图片列表:', imageUrls)
      return imageUrls
    },
    
    // 图片加载错误处理
    onImageError(img, index) {
      console.error('图片加载失败:', img, index)
      uni.showToast({
        title: '图片加载失败',
        icon: 'none'
      })
    },
    
    // 完成图片加载错误处理
    onCompletionImageError(img, index) {
      console.error('完成图片加载失败:', img, index)
      uni.showToast({
        title: '完成图片加载失败',
        icon: 'none'
      })
    },
    
    // 预览图片
    previewImage(current, urls) {
      console.log('预览图片:', current, urls)
      uni.previewImage({
        current: current,
        urls: urls
      })
    },
    
    // 预览完成图片
    previewCompletionImage(current, urls) {
      console.log('预览完成图片:', current, urls)
      uni.previewImage({
        current: current,
        urls: urls
      })
    },
    
    // 获取状态样式
    getStatusClass(status) {
      const classMap = {
        '待派单': 'status-pending',
        '已派单': 'status-dispatched',
        '已接单': 'status-accepted',
        '处理中': 'status-processing',
        '已完成': 'status-completed',
        '已拒绝': 'status-rejected',
        '已转派': 'status-rejected'
      }
      return classMap[status] || 'status-pending'
    },
    
    // 获取创建用户类型文本
    getCreateUserTypeText(type) {
      const typeMap = {
        '1': '管理员',
        '2': '房东',
        '3': '租户'
      }
      return typeMap[type] || '未知'
    },
    
    // 获取时间线圆点样式
    getTimelineDotClass(status) {
      const classMap = {
        '待派单': 'dot-pending',
        '已派单': 'dot-dispatched',
        '已接单': 'dot-accepted',
        '处理中': 'dot-processing',
        '已完成': 'dot-completed',
        '已拒绝': 'dot-rejected',
        '已转派': 'dot-rejected'
      }
      return classMap[status] || 'dot-default'
    },
    
    // 获取状态标签样式
    getStatusTagClass(status) {
      const classMap = {
        '待派单': 'tag-pending',
        '已派单': 'tag-dispatched',
        '已接单': 'tag-accepted',
        '处理中': 'tag-processing',
        '已完成': 'tag-completed',
        '已拒绝': 'tag-rejected',
        '已转派': 'tag-rejected'
      }
      return classMap[status] || 'tag-default'
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 格式化短时间
    formatTimeShort(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${month}-${day} ${hours}:${minutes}`;
    },

    // 获取完整地址
    getFullAddress() {
      let address = '';
      if (this.workorderInfo.provinceName) {
        address += this.workorderInfo.provinceName + ' ';
      }
      if (this.workorderInfo.cityName) {
        address += this.workorderInfo.cityName + ' ';
      }
      if (this.workorderInfo.districtName) {
        address += this.workorderInfo.districtName + ' ';
      }
      if (this.workorderInfo.streetName) {
        address += this.workorderInfo.streetName + ' ';
      }
      if (this.workorderInfo.villageName) {
        address += this.workorderInfo.villageName + ' ';
      }
      if (this.workorderInfo.door) {
        address += this.workorderInfo.door;
      } else if (this.workorderInfo.address) {
        address += this.workorderInfo.address;
      }
      return address.trim();
    }
  }
}
</script>

<style lang="scss" scoped>
.workorder-detail-container {
  background-color: #f5f6f7;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .nav-back {
    color: #007AFF;
    font-size: 28rpx;
  }
  
  .nav-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
  
  .nav-edit {
    color: #007AFF;
    font-size: 28rpx;
  }
}

.detail-section {
  margin: 20rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    padding-left: 20rpx;
    border-left: 4rpx solid #007AFF;
    display: flex;
    align-items: center;
    
    .iconfont {
      margin-right: 10rpx;
      font-size: 28rpx;
      color: #007AFF;
    }
  }
  
  .info-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    
    .info-row {
      display: flex;
      margin-bottom: 20rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .info-label {
        font-size: 28rpx;
        color: #666;
        width: 160rpx;
        flex-shrink: 0;
      }
      
      .info-value {
        font-size: 28rpx;
        color: #333;
        flex: 1;
        
        &.description {
          color: #666;
          line-height: 1.5;
        }

        &.address {
          color: #666;
          line-height: 1.5;
        }

        &.price {
          font-weight: bold;
          color: #fa8c16;
        }
        
        &.status {
          font-weight: bold;
          
                  &.status-pending {
          color: #fa8c16;
        }
        
        &.status-dispatched {
          color: #52c41a;
        }
        
        &.status-accepted {
          color: #1890ff;
        }
        
        &.status-processing {
          color: #722ed1;
        }
        
        &.status-completed {
          color: #52c41a;
        }
        
        &.status-rejected {
          color: #ff4d4f;
        }
        }
      }
      
      .image-list {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
        
        .repair-image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 8rpx;
          border: 1px solid #eee;
        }
      }
    }
  }
  
  .timeline-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    
    .timeline-item {
      position: relative;
      display: flex;
      margin-bottom: 40rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .timeline-dot {
        width: 16rpx;
        height: 16rpx;
        border-radius: 50%;
        margin-right: 30rpx;
        flex-shrink: 0;
        margin-top: 8rpx;
        z-index: 2;
        
        &.dot-pending {
          background-color: #d9d9d9;
        }
        
        &.dot-dispatched {
          background-color: #52c41a;
        }
        
        &.dot-accepted {
          background-color: #1890ff;
        }
        
        &.dot-processing {
          background-color: #722ed1;
        }
        
        &.dot-completed {
          background-color: #52c41a;
        }
        
        &.dot-rejected {
          background-color: #ff4d4f;
        }
        
        &.dot-default {
          background-color: #d9d9d9;
        }
      }
      
      .timeline-line {
        position: absolute;
        left: 8rpx;
        top: 24rpx;
        width: 2rpx;
        height: calc(100% + 16rpx);
        background-color: #e8e8e8;
        z-index: 1;
      }
      
      .timeline-content {
        flex: 1;
        
        .timeline-status-tag {
          display: inline-block;
          padding: 8rpx 16rpx;
          border-radius: 20rpx;
          font-size: 24rpx;
          margin-bottom: 10rpx;
          
          &.tag-pending {
            background-color: #f5f5f5;
            color: #666;
          }
          
          &.tag-dispatched {
            background-color: #f6ffed;
            color: #52c41a;
          }
          
          &.tag-accepted {
            background-color: #e6f7ff;
            color: #1890ff;
          }
          
          &.tag-processing {
            background-color: #f0f5ff;
            color: #722ed1;
          }
          
          &.tag-completed {
            background-color: #f6ffed;
            color: #52c41a;
          }
          
          &.tag-rejected {
            background-color: #fff2f0;
            color: #ff4d4f;
          }
          
          &.tag-default {
            background-color: #f5f5f5;
            color: #666;
          }
        }
        
        .timeline-time-short {
          font-size: 26rpx;
          color: #333;
          margin-bottom: 5rpx;
        }
        
        .timeline-time-full {
          font-size: 22rpx;
          color: #999;
          margin-bottom: 10rpx;
        }
        
        .timeline-operator {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 8rpx;
        }
        
        .timeline-log {
          font-size: 26rpx;
          color: #333;
          background-color: #f8f9fa;
          padding: 15rpx;
          border-radius: 8rpx;
          border-left: 4rpx solid #007AFF;
          line-height: 1.4;
        }
        
        .timeline-completion-info {
          margin-top: 15rpx;
          
          .location-info {
            display: flex;
            align-items: center;
            margin-bottom: 15rpx;
            
            .info-label {
              font-size: 24rpx;
              color: #666;
              margin-right: 10rpx;
            }
            
            .location-coords {
              font-size: 24rpx;
              color: #333;
              background-color: #f0f9ff;
              padding: 8rpx 12rpx;
              border-radius: 6rpx;
              border: 1px solid #bae7ff;
            }
          }
          
          .completion-images {
            .info-label {
              display: block;
              font-size: 24rpx;
              color: #666;
              margin-bottom: 10rpx;
            }
            
            .image-grid {
              display: flex;
              flex-wrap: wrap;
              gap: 10rpx;
              
              .completion-image {
                width: 80rpx;
                height: 80rpx;
                border-radius: 6rpx;
                border: 1px solid #eee;
              }
            }
          }
        }
      }
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1px solid #eee;
  display: flex;
  gap: 20rpx;
  
  .action-btn {
    flex: 1;
    padding: 20rpx 0;
    border-radius: 50rpx;
    font-size: 28rpx;
    font-weight: bold;
    border: none;
    
    &.accept {
      background-color: #52c41a;
      color: #fff;
    }
    
    &.reject {
      background-color: #ff4d4f;
      color: #fff;
    }
  }
}
</style> 